<!DOCTYPE html>
<html>
<head>
<title>dept.html</title>

<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">

</head>

<body>

	<table cellpadding="5" cellspacing="0" border="1" width="50%"
		id="deptTable">

		<tr>
			<td>部门编号</td>
			<td>部门名称</td>
			<td>部门地址</td>
		</tr>

	</table>
	<p></p>
	<button id="loadbtn">加载部门数据</button>
</body>

<script type="text/javascript">

	window.onload = function() {

		var xmlHttpRequest = null;
		var tableroot = document.getElementById("deptTable");
		// 创建xmlHttpRequest对象
		create();
		document.getElementById("loadbtn").addEventListener("click", function(e) {

			xmlHttpRequest.open("post", "deptServlet/loadDepts");
			xmlHttpRequest.send(null);
			// 异步请求验证
			xmlHttpRequest.onreadystatechange = function() {
				// 判断是否正确接收
				if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
					clearNodes();
					var content = xmlHttpRequest.responseXML; // 直接获取DOM对象,操作DOM
					var depts = content.getElementsByTagName("dept");
					for (var i = 0; i < depts.length; i++) {
						var trEle = document.createElement("tr");
						trEle.setAttribute("id", "dept" + i);
						var deptnode = depts.item(i);
						var count = deptnode.childElementCount;
						for (var j = 0; j < count; j++) {
							var dno = document.createElement("td");
							dno.textContent = deptnode.childNodes.item(j).textContent;
							trEle.appendChild(dno);
						}
						tableroot.appendChild(trEle);
					}

				}

			}

		}, false);

		// 清除数据
		function clearNodes() {

			// 每次点击加载的时候清除之前的所有的数据，读出所有的tr, 只要属性中存在dept-*的id属性就干掉
			var trNodes = document.getElementsByTagName("tr");
			var len = trNodes.length;
			// 循环删除
			for (var i = 0; i < len; i++) {
				var trnode = trNodes.item(1);
				if (trnode) {
					tableroot.removeChild(trnode);
				}
			}

		}


		// 创建Ajax对象
		function create() {
			if (window.XMLHttpRequest) {
				// 说明是非IE浏览器
				xmlHttpRequest = new XMLHttpRequest();
			} else {
				xmlHttpRequest = new ActiveXObject("Microsoft.XMLHttp");
			}
		}
	}
</script>


</html>
